<?php

namespace App\Console\Commands;

use App\Admin\Models\SiteCompany;
use App\Store\Models\Financial\Statements\Voucher;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use App\Store\Models\Account\SiteStore;
use App\Store\Models\Financial\Statements\FinancialStatementsProfit;

use App\Store\Models\Financial\Statements\Moneylog as FinancialStatementsMoneylog;
use App\Store\Models\Financial\Statements\Subject;
use App\Store\Models\Order\OrderDeposit;
use App\Store\Models\Order\OrderMaintenance;
use App\Store\Models\Order\OrderRecharge;
use App\Store\Models\Order\OrderSalesGoods;

class FinancialProfit extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'command:FinancialProfit';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '生成利润表';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        Log::info('生成利润表开始');

        //  今天获取昨天的数据
        $yesterday = date('Y-m-d', strtotime('-1 day'));
        $start_time = strtotime($yesterday);
        $end_time = $start_time + 86399; // 24*60*60 - 1

        $this->executeProfit($start_time, $end_time,0,0);
        Log::info('生成利润表结束');
        return 0;
    }

    public function executeProfit($start_time, $end_time, $cp_id=0,$store_id = 0)
    {
        // 参数验证
        if ($start_time > $end_time) {
            Log::info('开始时间不能大于结束时间');
            return false;
        }

        // 获取科目列表 - 使用缓存或更高效的查询
        if($cp_id>0){
            $this->execProfit($start_time,$end_time,$cp_id,$store_id);
        }else{
            $companyList =SiteCompany::query()
                ->where('is_del',1)
                ->where('audit_status', 3)
                ->get(['id', 'company_name'])
                ->toArray();
            foreach ($companyList as $company){
                $cp_id = $company['id'];
                $this->execProfit($start_time,$end_time,$cp_id,0);
            }
        }

        return true;
    }

    public function getVocher($list, $subjectList)
    {
        // 定义所有需要计算的科目
        $items = [
            1 => ['codes' => ['6001'], 'type' => 'revenue'], // 营业收入
            2 => ['codes' => ['6401'], 'type' => 'expense'], // 营业成本
            3 => ['codes' => ['6403'], 'type' => 'expense'], // 税金及附加
            4 => ['codes' => ['640301'], 'type' => 'expense'], // 消费税
            5 => ['codes' => ['640302'], 'type' => 'expense'], // 营业税
            6 => ['codes' => ['640303'], 'type' => 'expense'], // 城市维护建设税
            7 => ['codes' => ['640304'], 'type' => 'expense'], // 资源税
            8 => ['codes' => ['640305'], 'type' => 'expense'], // 土地增值税
            9 => ['codes' => ['640306'], 'type' => 'expense'], // 城镇土地使用税等
            10 => ['codes' => ['640307'], 'type' => 'expense'], // 教育费附加等
            11 => ['codes' => ['6601'], 'type' => 'expense'], // 销售费用
            12 => ['codes' => ['660101'], 'type' => 'expense'], // 商品维修费
            13 => ['codes' => ['660102'], 'type' => 'expense'], // 广告费和业务宣传费
            14 => ['codes' => ['6602'], 'type' => 'expense'], // 管理费用
            15 => ['codes' => ['660201'], 'type' => 'expense'], // 开办费
            16 => ['codes' => ['660202'], 'type' => 'expense'], // 业务招待费
            17 => ['codes' => ['660203'], 'type' => 'expense'], // 研究费用
            18 => ['codes' => ['6603'], 'type' => 'expense'], // 财务费用
            19 => ['codes' => ['660301'], 'type' => 'expense'], // 利息费用
            20 => ['codes' => ['6111'], 'type' => 'revenue'], // 投资收益
            22 => ['codes' => ['630101', '630102'], 'type' => 'revenue'], // 营业外收入
            23 => ['codes' => ['630101'], 'type' => 'revenue'], // 政府补助
            24 => ['codes' => ['671101', '671102', '671103', '671104', '671105', '671106'], 'type' => 'expense'], // 营业外支出
            25 => ['codes' => ['671101'], 'type' => 'expense'], // 坏账损失
            26 => ['codes' => ['671102'], 'type' => 'expense'], // 无法收回的长期债券投资损失
            27 => ['codes' => ['671103'], 'type' => 'expense'], // 无法收回的长期股权投资损失
            28 => ['codes' => ['671104'], 'type' => 'expense'], // 自然灾害等不可抗力因素造成的损失
            29 => ['codes' => ['671105'], 'type' => 'expense'], // 税收滞纳金
            31 => ['codes' => ['6801'], 'type' => 'expense'], // 所得税费用
        ];


        $results = [];
        $subject = new Subject();

        // 初始化所有结果 - 包括带前缀的键
        foreach ($items as $key => $item) {
            $results["debit_$key"] = 0;
            $results["credit_$key"] = 0;
        }

        // 处理每个凭证项目
        foreach ($list as $item) {
            foreach ($items as $key => $config) {
                $codeMap = $subject->getSubjectNumbers($subjectList, $config['codes']);
                if (in_array($item['serial_number'], $codeMap)) {
                    $results["debit_$key"] += $item['debit_amount'];
                    $results["credit_$key"] += $item['credit_amount'];
                }
            }
        }

        // 计算每个项目的净额
        foreach ($items as $key => $config) {
            $debit = $results["debit_$key"] ?? 0;
            $credit = $results["credit_$key"] ?? 0;

            if ($config['type'] === 'revenue') {
                $results[$key] = $credit - $debit; // 收入类：贷方减借方
            } else {
                $results[$key] = $debit - $credit; // 费用类：借方减贷方
            }
        }

        // 计算衍生项目
        // 21=1-2-3-11-14-18+20
        $results[21] = $results[1] - $results[2] - $results[3] - $results[11] - $results[14] - $results[18] + $results[20];

        // 利润总额30=21+22-24
        $results[30] = $results[21] + $results[22] - $results[24];

        // 净利润32=30-31
        $results[32] = $results[30] - $results[31];

        // 返回所有结果（1到32）
        $finalResults = [];
        for ($i = 1; $i <= 32; $i++) {
            $finalResults["data_key_$i"] = $results[$i] ?? 0;
        }

        return $finalResults;

    }


    public function execProfit($start_time,$end_time,$cp_id=0,$store_id=0)
    {
        $subjectList = Subject::query()
            ->where(function ($query) use ($cp_id) {
                $query->where('cp_id', $cp_id)
                    ->orWhere('cp_id', 0);
            })
            ->where('is_del', 1)
            ->whereNotNull('serial_number')
            ->select(['serial_number', 'upper_number'])
            ->get()
            ->toArray();
        // 构建查询条件
        $where = [
            ['voucher_date', '>=', $start_time],
            ['voucher_date', '<=', $end_time],
            ['cp_id', '=', $cp_id]
        ];

        if ($store_id > 0) {
            $where[] = ['store_id', '=', $store_id];
        }



        // 获取凭证列表
        $list = (new Voucher())->getVoucherList($where);
        if (empty($list)) {
            // 如果没有数据，可以记录日志或直接返回
            Log::info('未找到符合条件的凭证数据', [
                'start_time' => $start_time,
                'end_time' => $end_time,
                'store_id' => $store_id
            ]);
            return true;
        }
        // 按店铺分组数据
        $groupData = [];
        foreach ($list as $item) {
            $groupData[$item['store_id']][] = $item;
        }

        // 批量处理数据
        $year = date('Y', $start_time);
        $month = date('m', $start_time);
        $date = date('Y-m-d', $start_time);

        foreach ($groupData as $storeId => $groupItems) {
            $cp_id = $groupItems[0]['cp_id'] ?? 0;

            // 计算财务数据
            $data = $this->getVocher($groupItems, $subjectList);

            // 构建完整数据
            $financialData = array_merge($data, [
                'store_id' => $storeId,
                'year' => $year,
                'month' => $month,
                'cp_id' => $cp_id,
                'date' => $date,
                'create_at'=>time(),
                'update_at'=>time()
            ]);

            // 构建查询条件
            $params = [
                'store_id' => $storeId,
                'year' => $year,
                'month' => $month,
                'cp_id' => $cp_id,
                'date' => $date
            ];

            // 使用updateOrCreate简化操作
            FinancialStatementsProfit::query()->updateOrCreate($params, $financialData);
        }

        return  true;
    }

}
